package com.run.runbbs.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.run.runbbs.common.dto.MessageDto;
import com.run.runbbs.common.lang.Result;
import com.run.runbbs.entity.Message;
import com.run.runbbs.entity.User;
import com.run.runbbs.service.impl.CommentService;
import com.run.runbbs.service.impl.MessageService;
import com.run.runbbs.service.impl.PostService;
import com.run.runbbs.service.impl.UserService;
import com.run.runbbs.util.Constant;
import com.run.runbbs.util.DateUtils;
import com.run.runbbs.util.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class MessageController implements Constant {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private PostService postService;
    @Autowired
    private JwtUtils jwtUtils;

    //获取会话列表,每个会话显示最新的一条消息，用户信息，消息未读数。
    @GetMapping("/getConversationList")
    public Result getConversationList(int userId,int offset){
        List<Message> conversations=messageService.findConversations(userId,offset,10);
        List<Map<String,Object>> conversationList=new ArrayList<>();
        if(conversations!=null){
            for(Message message :conversations){
                Map<String,Object> map=new HashMap<>();
                //把时间改成距离当前时间多久
                String fromNow= DateUtils.fromToday(message.getCreateTime());
                MessageDto messageDto=new MessageDto();
                BeanUtils.copyProperties(message,messageDto);
                messageDto.setFromNow(fromNow);

                map.put("conversation",messageDto);
                map.put("unreadCount",messageService.findLetterUnreadCount(userId,message.getConversationId()));

                int targetId=userId==message.getFromId()?message.getToId():message.getFromId();
                User fromUser=userService.findUserById(targetId);
                Map<String,Object> simpleFromUser=new HashMap<>();
                simpleFromUser.put("id",fromUser.getId());
                simpleFromUser.put("username",fromUser.getUsername());
                simpleFromUser.put("headerUrl",fromUser.getHeaderUrl());

                map.put("user",simpleFromUser);
                conversationList.add(map);
            }
        }
        return Result.success(conversationList);
    }
    //获取私信列表
    @GetMapping("/getLetterList")
    public Result getLetterList(String conversationId,int offset ,HttpServletRequest request){
        String jwt=request.getHeader("Authorization");
        System.out.println(jwt);
        int userId=Integer.parseInt(jwtUtils.getClaimByToken(jwt).getSubject());
        //先判断获取的私信列表是否属于本用户
        String[] splitId=conversationId.split("_");
        if(Integer.parseInt(splitId[0])==userId||Integer.parseInt(splitId[1])==userId){
            //私信列表
            List<Message> letters=messageService.findLetters(conversationId,offset,10);
            List<Map<String,Object>> letterList=new ArrayList<>();
            if(letters!=null){
                for(Message message : letters){
                    Map<String,Object> map=new HashMap<>();
                    //把时间改成距离当前时间多久
                    String fromNow= DateUtils.fromToday(message.getCreateTime());
                    MessageDto messageDto=new MessageDto();
                    BeanUtils.copyProperties(message,messageDto);
                    messageDto.setFromNow(fromNow);
                    map.put("letter",messageDto);

                    User fromUser=userService.findUserById(message.getFromId());
                    Map<String,Object> simpleFromUser=new HashMap<>();
                    simpleFromUser.put("id",fromUser.getId());
                    simpleFromUser.put("username",fromUser.getUsername());
                    simpleFromUser.put("headerUrl",fromUser.getHeaderUrl());

                    map.put("fromUser",simpleFromUser);

                    letterList.add(map);
                }
            }
            //获取成功，设置私信已读
            List<Integer> ids=getLetterIds(letters,userId);
            if(!ids.isEmpty()){
                messageService.readMessage(ids);
            }
            return Result.success(letterList);
        }else{
            return Result.fail("您不能看别人的私信！");
        }
    }

    //添加私信
    @PostMapping("/sendLetter")
    public Result sendLetter(String toId,String content,HttpServletRequest request){
        String jwt=request.getHeader("Authorization");
        System.out.println(jwt);
        int userId=Integer.parseInt(jwtUtils.getClaimByToken(jwt).getSubject());
        Message message=new Message();
        message.setFromId(userId);
        message.setToId(Integer.parseInt(toId));
        if(message.getFromId()<message.getToId()){
            message.setConversationId(message.getFromId()+"_"+message.getToId());
        }else{
            message.setConversationId(message.getToId()+"_"+message.getFromId());
        }
        message.setContent(content);
        message.setCreateTime(new Date());
        messageService.addMessage(message);
        return Result.success("私信发送成功！");
    }

    //获取未读私信的id集合
    private List<Integer> getLetterIds(List<Message> letterList,int userId){
        List<Integer> ids=new ArrayList<>();
        if(letterList!=null){
            for(Message message : letterList){
                if(userId==message.getToId()&&message.getStatus()==0){
                    ids.add(message.getId());
                }

            }
        }
        return ids;
    }

//    //获取消息通知
//    @GetMapping("/getNotice")
//    public Result getNotice(HttpServletRequest request){
//        int userId=jwtUtils.getUserId(request);
//        Map<String,Object> result=new HashMap<>();
//        //查询评论类通知
//        Message message=messageService.findLatestNotice(userId,TOPIC_COMMENT);
//        Map<String,Object> messageVo=new HashMap<>();
//        if(message!=null){
//            messageVo.put("message",message);
//            String content= HtmlUtils.htmlUnescape(message.getContent());
//            Map<String,Object> data= JSONObject.parseObject(content,HashMap.class);
//            messageVo.put("user",userService.findSimpleUserById((Integer) data.get("userId")));
//            messageVo.put("entityType",data.get("entityType"));
//            messageVo.put("entityId",data.get("entityId"));
//            messageVo.put("postId",data.get("postId"));
//
//            int count=messageService.findNoticeCount(userId,TOPIC_COMMENT);
//            messageVo.put("count",count);
//
//            int unread=messageService.findNoticeUnreadCount(userId,TOPIC_COMMENT);
//            messageVo.put("unread",unread);
//        }
//        result.put("commentNotice",messageVo);
//
//        //查询点赞类通知
//        message=messageService.findLatestNotice(userId,TOPIC_LIKE);
//        messageVo=new HashMap<>();
//        if(message!=null){
//            messageVo.put("message",message);
//            String content= HtmlUtils.htmlUnescape(message.getContent());
//            Map<String,Object> data= JSONObject.parseObject(content,HashMap.class);
//            messageVo.put("user",userService.findSimpleUserById((Integer) data.get("userId")));
//            messageVo.put("entityType",data.get("entityType"));
//            messageVo.put("entityId",data.get("entityId"));
//            messageVo.put("postId",data.get("postId"));
//
//            int count=messageService.findNoticeCount(userId,TOPIC_LIKE);
//            messageVo.put("count",count);
//
//            int unread=messageService.findNoticeUnreadCount(userId,TOPIC_LIKE);
//            messageVo.put("unread",unread);
//        }
//
//        result.put("likeNotice",messageVo);
//
//        //查询关注类通知
//        message=messageService.findLatestNotice(userId,TOPIC_FOLLOW);
//        messageVo=new HashMap<>();
//        if(message!=null){
//            messageVo.put("message",message);
//            String content= HtmlUtils.htmlUnescape(message.getContent());
//            Map<String,Object> data= JSONObject.parseObject(content,HashMap.class);
//            messageVo.put("user",userService.findSimpleUserById((Integer) data.get("userId")));
//            messageVo.put("entityType",data.get("entityType"));
//            messageVo.put("entityId",data.get("entityId"));
//
//            int count=messageService.findNoticeCount(userId,TOPIC_FOLLOW);
//            messageVo.put("count",count);
//
//            int unread=messageService.findNoticeUnreadCount(userId,TOPIC_FOLLOW);
//            messageVo.put("unread",unread);
//        }
//        result.put("followNotice",messageVo);
//
//        //查询所有通知未读数量
//        int noticeUnreadCount=messageService.findNoticeUnreadCount(userId,null);
//
//        result.put("noticeUnreadCount",noticeUnreadCount);
//        return Result.success(result);
//    }

    @GetMapping("/getNoticeUnreadCount")
    public Result getNoticeUnreadCount(HttpServletRequest request){
        int userId=jwtUtils.getUserId(request);
        int noticeUnreadCount=messageService.findNoticeUnreadCount(userId,null);
        return  Result.success(MapUtil.builder()
                .put("noticeUnreadCount",noticeUnreadCount)
                .map());
    }

    @GetMapping("/getNotices")
    public Result getNotices(String topic,int offset,HttpServletRequest request){
        int userId=jwtUtils.getUserId(request);

        List<Message> messages=messageService.findNotices(userId,topic,offset,10);
        List<Map<String,Object>> noticeVoList=new ArrayList<>();
        if(messages!=null){
            for(Message notice:messages){
                Map<String,Object> map=new HashMap<>();

                String content=HtmlUtils.htmlUnescape(notice.getContent());
                Map<String,Object> data=JSONObject.parseObject(content,HashMap.class);
                //自己的不通知。
                if((Integer) data.get("userId")!=userId){
                    map.put("user",userService.findSimpleUserById((Integer) data.get("userId")));
                    map.put("time",notice.getCreateTime());
                    if(topic.equals(TOPIC_COMMENT)){
                        //获取评论的内容，当初entityId存的就是评论的Id。
                        String commentContent=commentService.findCommentById((Integer) data.get("commentId")).getContent();
                        map.put("commentContent",commentContent);

                        //评论的是帖子，传被评论帖子的标题过去    回复的是评论，传被回复的评论的内容过去。
                        if((Integer) data.get("entityType")==ENTITY_TYPE_POST){
                            String postTitle=postService.findPost((Integer)data.get("postId")).getTitle();
                            map.put("postTitle", postTitle);
                        }else if((Integer) data.get("entityType")==ENTITY_TYPE_COMMENT){
                            //被回复的内容。（别人回复了我的评论，发送通知，右边显示我的评论内容）
                            int byReplyCommentId=commentService.findCommentById((Integer) data.get("commentId")).getEntityId();
                            String byReplyContent=commentService.findCommentById(byReplyCommentId).getContent();
                            map.put("beReplyContent",byReplyContent);
                        }
                        map.put("postId",data.get("postId"));
                    }else if(topic.equals(TOPIC_LIKE)){
                        //暂时点赞的只有帖子。
                        String postTitle=postService.findPost((Integer)data.get("postId")).getTitle();
                        map.put("postTitle", postTitle);
                        map.put("postId",data.get("postId"));
                    }
                    noticeVoList.add(map);
                }



            }
        }

//        //设置已读
//        List<Integer> ids=getLetterIds(messages,userId);
//        if(!ids.isEmpty()){
//            messageService.readMessage(ids);
//        }

        return Result.success(noticeVoList);
    }



}
